package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.admin.query.HeaderFieldsQuery;
import org.jsola.admin.vo.HeaderFieldsVO;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.TreatmentDisposeEventAddDTO;
import org.jsola.hr.dto.TreatmentDisposeEventUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.HeaderFieldsSocQuery;
import org.jsola.hr.query.SocStatisticalQuery;
import org.jsola.hr.query.TreatmentDisposeEventExportQuery;
import org.jsola.hr.query.TreatmentDisposeEventQuery;
import org.jsola.hr.service.ITreatmentDisposeEventService;
import org.jsola.hr.vo.EmpSocInfoStatisticalExportVO;
import org.jsola.hr.vo.ImportExcelResultListVO;
import org.jsola.hr.vo.TreatmentDisposeEventListVO;
import org.jsola.hr.vo.TreatmentDisposeEventVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;


/**
 * 待遇处理事件
 *
 * @author zhr
 */
@RestController("hrTreatmentDisposeEventController")
@RequestMapping(HrConstants.API_PATH + "/v1/treatmentDisposeEvents")
public class TreatmentDisposeEventController implements ITreatmentDisposeEventControllerAPI {

    @Autowired
    private ITreatmentDisposeEventService treatmentDisposeEventService;

    @Override
    @PostMapping
    public Result<TreatmentDisposeEventVO> save(@Valid @RequestBody TreatmentDisposeEventAddDTO treatmentDisposeEventAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增待遇处理事件权限校验

        return Result.success(
                treatmentDisposeEventService.save(treatmentDisposeEventAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody TreatmentDisposeEventUpdateDTO treatmentDisposeEventUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改待遇处理事件权限校验

        int count = treatmentDisposeEventService.update(treatmentDisposeEventUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{treatmentDisposeEventId}")
    public Result<Integer> delete(@PathVariable String treatmentDisposeEventId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除待遇处理事件权限校验

        int count = treatmentDisposeEventService.deleteByIds(tokenUser, treatmentDisposeEventId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] treatmentDisposeEventIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除待遇处理事件权限校验

        int count = treatmentDisposeEventService.deleteByIds(tokenUser, treatmentDisposeEventIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{treatmentDisposeEventId}")
    public Result<TreatmentDisposeEventVO> findById(@PathVariable String treatmentDisposeEventId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看待遇处理事件权限校验

        return Result.success(
                treatmentDisposeEventService.selectById(treatmentDisposeEventId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<TreatmentDisposeEventListVO>> listAll(@Valid TreatmentDisposeEventQuery treatmentDisposeEventQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看待遇处理事件权限校验

        return Result.success(
                treatmentDisposeEventService.select(treatmentDisposeEventQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<TreatmentDisposeEventListVO>> page(@Valid TreatmentDisposeEventQuery treatmentDisposeEventQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                treatmentDisposeEventService.selectPage(treatmentDisposeEventQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PutMapping("/finishOrUnfinishedEvent")
    public Result<String> finishOrUnfinishedEvent(@RequestParam("eventId") String eventId,
                                                  @RequestParam("status") Boolean status) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        treatmentDisposeEventService.finishOrUnfinishedEvent(eventId, status, tokenUser);
        return Result.success();
    }

    @Override
    @GetMapping("/selectEventInfoById/{eventId}")
    public Result<TreatmentDisposeEventVO> selectEventInfoById(@PathVariable String eventId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                treatmentDisposeEventService.selectEventInfoById(eventId, tokenUser)
        );
    }

    @Override
    @PostMapping("/importEvent/{templateId}")
    public Result<ImportExcelResultListVO<Map<String, String>>> importEvent(@PathVariable String templateId,
                                                                            @RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        return Result.success(
                treatmentDisposeEventService.importEvent(excelFile, templateId, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/exportErrorList")
    public ResponseEntity<Resource> exportErrorList(@RequestBody ImportExcelResultListVO<Map<String, String>> errorInfo) {
        TokenUser tokenUser = UserContext.getUser();
        String exportPath = treatmentDisposeEventService.errorListExport(errorInfo);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(exportPath).getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(exportPath));
    }

    @Override
    @GetMapping("/selectEventByEmpId/{empId}")
    public Result<List<TreatmentDisposeEventVO>> selectEventByEmpId(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        return Result.success(
                treatmentDisposeEventService.selectEventByEmpId(empId, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/export")
    public ResponseEntity<Resource> export(@RequestBody TreatmentDisposeEventExportQuery query) {
        TokenUser tokenUser = UserContext.getUser();
        //查询到导出的数据
        String exportPath = treatmentDisposeEventService.export(query, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(exportPath).getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(exportPath));
    }

    @Override
    @GetMapping("/getEventExportHead")
    public Result<HeaderFieldsVO> getEventExportHead(@RequestParam HeaderFieldsQuery headerQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工参保信息表权限校验

        return Result.success(
                treatmentDisposeEventService.getEventExportHead(headerQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/existsNotFinish/{templateId}")
    public Result<Boolean> existsNotFinish(@PathVariable String templateId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工参保信息表权限校验

        return Result.success(
                !CollectionUtils.isEmpty(treatmentDisposeEventService
                        .selectNotFinishEventByTemplateId(templateId, tokenUser))
        );
    }
}

